package cool.taomu.toolkit.git.service

import cool.taomu.toolkit.git.JGitTools
import cool.taomu.toolkit.git.entity.FileWriteEntity
import cool.taomu.toolkit.git.entity.FileWriteEntity.OperationType
import cool.taomu.toolkit.utils.FileTools
import java.io.File
import java.util.ArrayList
import java.util.List
import javax.inject.Inject
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.StringUtils
import org.eclipse.jgit.api.TransportConfigCallback
import org.eclipse.jgit.transport.CredentialsProvider
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory

@Accessors
@Deprecated
class JGitService {

	val static LOG = LoggerFactory.getLogger(JGitService);

	@Inject
	JGitTools jgit;

	var List<FileWriteEntity> filelist = new ArrayList<FileWriteEntity>();

	def void init(String path) {
		this.init("", path);
	}

	def void init(String basePath, String path) {
		jgit.setRepository(basePath, path);
		if (!jgit.isReprositoryExists) {
			jgit.init;
		}
	}

	def void auth(CredentialsProvider cp) {
		this.jgit.cp = cp;
	}

	def void auth(TransportConfigCallback ssh) {
		this.jgit.ssh = ssh;
	}

	def void addPath(String path) {
		filelist.add(new FileWriteEntity(path).ADD());
	}

	def void addFile(String filename, String content) {
		filelist.add(new FileWriteEntity(filename, content));
	}

	def void rm(String path) {
		filelist.add(new FileWriteEntity(path).RM());
	}

	def void commit(String version) {
		// 文件写入并入库
		val subPaths = new ArrayList<String>();
		val rmPaths = new ArrayList<String>();
		val basePath = jgit.path;
		filelist.forEach [
			val spath = it.path;
			if (it.type == OperationType.ADD) {
				LOG.info("添加文件:{}", spath);
				if (StringUtils.isNotBlank(it.content.trim)) {
					FileUtils.writeStringToFile(new File(spath), it.content.trim, "UTF-8", false);
				}
				var subPath = FileTools.getSubdirectory(#[basePath.trim, File.separator].join(), spath, "/").trim;
				if (StringUtils.isNotBlank(subPath)) {
					subPaths.add(subPath);
				}
			} else if (it.type == OperationType.RM) {
				LOG.info("删除文件:{}", spath);
				var subPath = FileTools.getSubdirectory(#[basePath.trim, File.separator].join(), spath, "/").trim;
				if (StringUtils.isNotBlank(subPath)) {
					rmPaths.add(subPath);
				}
			}
		]
		if (subPaths.size > 0) {
			jgit.repository = basePath;
			if (!jgit.reprositoryExists) {
				jgit.init();
			}
			jgit.autoCommit = true;
			LOG.info("向本地库添加文件 {} 份", subPaths.size);
			jgit.addAndCommit(#["add v", version, "\n", subPaths.join("\n")].join(), [
				subPaths.forEach [ path |
					it.addFilepattern(path);
				]
			]);
		}
		if (rmPaths.size > 0) {
			jgit.repository = basePath;
			if (!jgit.reprositoryExists) {
				jgit.init();
			}
			jgit.autoCommit = true;
			LOG.info("向本地库删除文件 {} 份", rmPaths.size);
			jgit.rmAndCommit(#["rm v", version, "\n", rmPaths.join("\n")].join(), [
				rmPaths.forEach [ path |
					it.addFilepattern(path);
				]
			]);
		}
		filelist.clear
	}
}
